package com.mcppro.aidatabase.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;
import java.util.List;

/**
 * 跨域配置
 * 
 * @author MCP Pro
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {

    // 硬编码配置，避免配置文件解析问题
    private final List<String> allowedOrigins = Arrays.asList(
            "http://localhost:3000",
            "http://localhost:8081",
            "http://127.0.0.1:3000",
            "http://127.0.0.1:8081",
            "http://localhost:8080",
            "http://127.0.0.1:8080",
            "http://localhost",      // 不带端口号的localhost
            "http://127.0.0.1"       // 不带端口号的127.0.0.1
    );
    
    private final List<String> allowedMethods = Arrays.asList(
            "GET", "POST", "PUT", "DELETE", "OPTIONS"
    );
    
    private final List<String> allowedHeaders = Arrays.asList("*");
    
    private final boolean allowCredentials = true;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                // 优先使用通配符模式，支持所有本地地址
                .allowedOriginPatterns(
                    "http://localhost",
                    "http://localhost:*", 
                    "http://127.0.0.1",
                    "http://127.0.0.1:*"
                )
                .allowedOrigins(allowedOrigins.toArray(new String[0]))
                .allowedMethods(allowedMethods.toArray(new String[0]))
                .allowedHeaders(allowedHeaders.toArray(new String[0]))
                .allowCredentials(allowCredentials)
                .maxAge(3600);
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(allowedOrigins);
        // 支持所有本地地址的通配符模式
        configuration.setAllowedOriginPatterns(Arrays.asList(
            "http://localhost",
            "http://localhost:*", 
            "http://127.0.0.1",
            "http://127.0.0.1:*"
        ));
        configuration.setAllowedMethods(allowedMethods);
        configuration.setAllowedHeaders(allowedHeaders);
        configuration.setAllowCredentials(allowCredentials);
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}